<template>
  <div class="viewContain">
    <el-form :model="listQuery" size="small" label-width="100px">
      <el-row>
        <el-col :xs="{ span: 24 }" :sm="{ span: 12 }" :md="{ span: 4 }" :xl="{ span: 4 }">
          <el-form-item label="商品编码 :">
            <el-input
              v-model="listQuery.code"
              placeholder="请输入"
              clearable
              @keyup.enter.native="handleSearch"
            />
          </el-form-item>
        </el-col>
        <el-col :xs="{ span: 24 }" :sm="{ span: 12 }" :md="{ span: 4 }" :xl="{ span: 4 }">
          <el-form-item label="商品名称 :">
            <el-input
              v-model="listQuery.name"
              placeholder="请输入"
              clearable
              @keyup.enter.native="handleSearch"
            />
          </el-form-item>
        </el-col>
        <el-col :xs="{ span: 24 }" :sm="{ span: 12 }" :md="{ span: 4 }" :xl="{ span: 4 }">
          <el-form-item label-width="20px">
            <el-button size="mini" type="primary" @click="handleSearch">查询</el-button>
            <el-button size="mini" type="primary" plain @click="handleReload">重置</el-button>
          </el-form-item>
        </el-col>
        <el-col :xs="{ span: 24 }" :sm="{ span: 12 }" :md="{ span: 12 }" :xl="{ span: 12 }" align="right">
          <el-form-item label-width="10px">
            <el-button v-if="isAdminRole==='1'" size="mini" type="primary" @click="handleAddGoods()">新增商品信息</el-button>
            <el-button v-if="isAdminRole==='1'" size="mini" type="primary" @click="handleDownLoad">模板下载</el-button>
            <el-upload
              v-if="isAdminRole==='1'"
              action="#"
              :limit="1"
              :on-exceed="handleExceed"
              :before-upload="beforeFileUpload"
              style="display:inline-block"
            >
              <el-button slot="trigger" size="mini" type="primary" @click="uploadFileType('importStock')">商品批量入库</el-button>
            </el-upload>
            <el-upload
              v-if="isAdminRole==='1'"
              action="#"
              :limit="1"
              :on-exceed="handleExceed"
              :before-upload="beforeFileUpload1"
              style="display:inline-block"
            >
              <el-button slot="trigger" size="mini" type="primary" @click="uploadFileType('importImg')">导入商品图片</el-button>
            </el-upload>
            <el-upload
              v-if="isAdminRole==='1'"
              action="#"
              :limit="1"
              :on-exceed="handleExceed"
              :before-upload="beforeFileUpload"
              style="display:inline-block"
            >
              <el-button slot="trigger" size="mini" type="primary" @click="uploadFileType('importGoods')">导入商品信息</el-button>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogFormVisible"
      :close-on-click-modal="false"
      @close="closeDialog"
    >
      <el-form ref="formData" :model="formData" size="small" label-width="150px" class="dialogFormHeight" :rules="rules">
        <el-row>
          <el-col :xs="{ span: 24 }" :sm="{ span: 12 }" :md="{ span: 12 }" :xl="{ span: 12 }">
            <el-form-item label="商品编码 :" prop="code">
              <el-input v-model="formData.code" placeholder="请输入" clearable :disabled="disabledCode" />
            </el-form-item>
          </el-col>
          <el-col :xs="{ span: 24 }" :sm="{ span: 12 }" :md="{ span: 12 }" :xl="{ span: 12 }">
            <el-form-item label="商品名称 :" prop="name">
              <el-input v-model="formData.name" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
          <el-col :xs="{ span: 24 }" :sm="{ span: 24 }" :md="{ span: 24 }" :xl="{ span: 24 }">
            <el-form-item label="商品介绍 :" prop="introduce">
              <el-input v-model="formData.introduce" type="textarea" :rows="2" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
          <el-col :xs="{ span: 24 }" :sm="{ span: 12 }" :md="{ span: 12 }" :xl="{ span: 12 }">
            <el-form-item label="成本价 :" prop="buyPrice">
              <el-input v-model="formData.buyPrice" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
          <el-col :xs="{ span: 24 }" :sm="{ span: 12 }" :md="{ span: 12 }" :xl="{ span: 12 }">
            <el-form-item label="出售价 :" prop="salePrice">
              <el-input v-model="formData.salePrice" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
          <el-col :xs="{ span: 24 }" :sm="{ span: 12 }" :md="{ span: 12 }" :xl="{ span: 12 }">
            <el-form-item label="生产地 :" prop="productAddr">
              <el-input v-model="formData.productAddr" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
          <el-col :xs="{ span: 24 }" :sm="{ span: 12 }" :md="{ span: 12 }" :xl="{ span: 12 }">
            <el-form-item label="发货地 :" prop="shipAddr">
              <el-input v-model="formData.shipAddr" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
          <el-col :xs="{ span: 24 }" :sm="{ span: 12 }" :md="{ span: 12 }" :xl="{ span: 12 }">
            <el-form-item label="商品型号 :" prop="model">
              <el-input v-model="formData.model" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
          <el-col :xs="{ span: 24 }" :sm="{ span: 12 }" :md="{ span: 12 }" :xl="{ span: 12 }">
            <el-form-item label="商品存放地 :" prop="location">
              <el-input v-model="formData.location" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
          <el-col :xs="{ span: 24 }" :sm="{ span: 12 }" :md="{ span: 12 }" :xl="{ span: 12 }">
            <el-form-item label="商品来源 :" prop="source">
              <el-input v-model="formData.source" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
          <el-col :xs="{ span: 24 }" :sm="{ span: 12 }" :md="{ span: 12 }" :xl="{ span: 12 }">
            <el-form-item label="库存量 :" prop="stock">
              <el-input v-model="formData.stock" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
          <el-col :xs="{ span: 24 }" :sm="{ span: 24 }" :md="{ span: 24 }" :xl="{ span: 24 }">
            <el-form-item label="商品图片 :" prop="photoList">
              <van-uploader
                v-model="updateFileList"
                multiple
                accept="image/jpeg"
                :preview-full-image="showPic"
                :max-count="30"
                :before-delete="deleteInsertPic"
                :before-read="beforeRead"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <div style="text-align:center">
          <el-button size="mini" type="primary" plain @click="handleClose">取消</el-button>
          <el-button size="mini" type="primary" @click="handleSave">确定</el-button>
        </div>
      </el-form>
    </el-dialog>
    <el-dialog
      :title="dialogTitle_distribute"
      :visible.sync="dialogFormVisible_distribute"
      width="400px"
      :close-on-click-modal="false"
      @close="closeDialog1"
    >
      <el-form ref="formData_distribute" :model="formData_distribute" size="small" :rules="rules_distribute" label-width="100px">
        <el-row>
          <el-col :xs="{ span: 24 }" :sm="{ span: 24 }" :md="{ span: 24 }" :xl="{ span: 24 }">
            <el-form-item label="商品编码 :" prop="code">
              <el-input v-model="formData_distribute.code" placeholder="请输入" disabled />
            </el-form-item>
          </el-col>
          <el-col :xs="{ span: 24 }" :sm="{ span: 24 }" :md="{ span: 24 }" :xl="{ span: 24 }">
            <el-form-item label="分配站点 :" prop="site">
              <el-select v-model="formData_distribute.site" placeholder="请选择" filterable clearable style="width:100%">
                <el-option
                  v-for="item in siteList"
                  :key="item.orgId"
                  :label="item.name"
                  :value="item.orgId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="{ span: 24 }" :sm="{ span: 24 }" :md="{ span: 24 }" :xl="{ span: 24 }">
            <el-form-item label="分配数量 :" prop="stock">
              <el-input v-model="formData_distribute.stock" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
        </el-row>
        <div style="text-align:center">
          <el-button size="mini" type="primary" plain @click="close_distribute">取消</el-button>
          <el-button size="mini" type="primary" @click="handleSave_distribute">确定</el-button>
        </div>
      </el-form>
    </el-dialog>
    <el-dialog
      :title="dialogTitle_detail"
      :visible.sync="dialogFormVisible_detail"
      width="60%"
      :close-on-click-modal="false"
    >
      <div class="goodDetail">
        <el-form size="small" label-width="150px" class="dialogFormHeight">
          <el-row>
            <el-col :xs="{ span: 24 }" :sm="{ span: 12 }" :md="{ span: 12 }" :xl="{ span: 12 }">
              <el-form-item label="商品编码: ">
                {{ goodsDetail.code }}
              </el-form-item>
            </el-col>
            <el-col :xs="{ span: 24 }" :sm="{ span: 12 }" :md="{ span: 12 }" :xl="{ span: 12 }">
              <el-form-item label="商品名称: ">
                {{ goodsDetail.name }}
              </el-form-item>
            </el-col>
            <el-col :xs="{ span: 24 }" :sm="{ span: 14 }" :md="{ span: 14 }" :xl="{ span: 14 }">
              <el-form-item label="商品介绍: ">
                {{ goodsDetail.introduce }}
              </el-form-item>
            </el-col>
            <el-col :xs="{ span: 24 }" :sm="{ span: 12 }" :md="{ span: 12 }" :xl="{ span: 12 }">
              <el-form-item label="商品成本(元): ">
                {{ Number(goodsDetail.buyPrice).toFixed(2) }}
              </el-form-item>
            </el-col>
            <el-col :xs="{ span: 24 }" :sm="{ span: 12 }" :md="{ span: 12 }" :xl="{ span: 12 }">
              <el-form-item label="商品售价(元): ">
                {{ Number(goodsDetail.salePrice).toFixed(2) }}
              </el-form-item>
            </el-col>
            <el-col :xs="{ span: 24 }" :sm="{ span: 12 }" :md="{ span: 12 }" :xl="{ span: 12 }">
              <el-form-item label="生产地: ">
                {{ goodsDetail.productAddr }}
              </el-form-item>
            </el-col>
            <el-col :xs="{ span: 24 }" :sm="{ span: 12 }" :md="{ span: 12 }" :xl="{ span: 12 }">
              <el-form-item label="发货地: ">
                {{ goodsDetail.shipAddr }}
              </el-form-item>
            </el-col>
            <el-col :xs="{ span: 24 }" :sm="{ span: 12 }" :md="{ span: 12 }" :xl="{ span: 12 }">
              <el-form-item label="商品型号: ">
                {{ goodsDetail.model }}
              </el-form-item>
            </el-col>
            <el-col :xs="{ span: 24 }" :sm="{ span: 12 }" :md="{ span: 12 }" :xl="{ span: 12 }">
              <el-form-item label="库存量: ">
                {{ goodsDetail.stock }}
              </el-form-item>
            </el-col>
            <el-col :xs="{ span: 24 }" :sm="{ span: 12 }" :md="{ span: 12 }" :xl="{ span: 12 }">
              <el-form-item label="创建时间:">
                {{ goodsDetail.createTime }}
              </el-form-item>
            </el-col>
            <el-col :xs="{ span: 24 }" :sm="{ span: 12 }" :md="{ span: 12 }" :xl="{ span: 12 }">
              <el-form-item label="商品来源: ">
                {{ goodsDetail.source }}
              </el-form-item>
            </el-col>
            <el-col :xs="{ span: 24 }" :sm="{ span: 12 }" :md="{ span: 12 }" :xl="{ span: 12 }">
              <el-form-item label="商品存放地: ">
                {{ goodsDetail.location }}
              </el-form-item>
            </el-col>
          </el-row>
          <div style="text-align:center" @click="closeDialogFormVisible_detail">
            <div v-for="item in goodsDetail.photoList" :key="item.id" style="text-align:center">
              <img class="img1" :src="item.photoName" alt="">
            </div>
            <el-button size="mini" type="primary" plain @click="handleClose">关闭</el-button>
          </div>
        </el-form>
      </div>
    </el-dialog>
    <el-table
      ref="table"
      v-loading="loading"
      fit
      stripe
      :data="tableData"
      border
      size="mini"
    >
      <el-table-column align="center" label="序号" type="index" width="50">
        <template slot-scope="scope">
          {{ (listQuery.pageNo - 1) * listQuery.pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column prop="name" align="center" label="商品名称" width="150" :show-overflow-tooltip="true" />
      <el-table-column prop="no" align="center" label="商品图片" width="150">
        <template slot-scope="scope">
          <!-- <img v-if="scope.row.photoList.length" v-image-preview :src="scope.row.photoList[0].photoName" alt="" width="40px" height="40px">
          <img v-else v-image-preview width="40px" height="40px" src="../../../assets/images/noneImg.jpg"> -->
          <el-image
            v-if="scope.row.photoList.length"
            style="width: 40px; height: 40px"
            :src="scope.row.photoList[0].photoName"
            :preview-src-list="[scope.row.photoList[0].photoName]"
          />
          <img v-else width="40px" height="40px" src="@/assets/images/noneImg.jpg">
        </template>
      </el-table-column>
      <el-table-column prop="code" align="center" label="商品编号" />
      <el-table-column prop="buyPrice" align="center" label="成本(元)">
        <template slot-scope="scope">
          {{ Number(scope.row.buyPrice).toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column prop="salePrice" align="center" label="售价(元)">
        <template slot-scope="scope">
          {{ Number(scope.row.salePrice).toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column prop="model" align="center" label="商品型号" />
      <el-table-column prop="stock" align="center" label="中心库存量" />
      <el-table-column align="center" label="操作" width="250">
        <template slot-scope="scope">
          <el-button class="text-button" size="mini" @click="handleDetail(scope.row.code)">详情</el-button>
          <el-button v-if="scope.row.status === '0' && isAdminRole ==='1'" class="text-button" size="mini" @click="handleOutshelf(scope.row.status, scope.row.code)">下架</el-button>
          <el-button v-if="scope.row.status === '1' && isAdminRole ==='1'" class="text-button" size="mini" @click="handleOutshelf(scope.row.status, scope.row.code)">上架</el-button>
          <el-button v-if="isAdminRole ==='1'" class="text-button" size="mini" @click="handleEdit(scope.row.code)">修改</el-button>
          <el-button v-if="isAdminRole ==='1'" class="text-button" size="mini" @click="handleImportStore(scope.row.code)">入库</el-button>
          <el-button v-if="isAdminRole ==='1'" class="text-button" size="mini" @click="handleDistribute(scope.row.code)">分配</el-button>
          <!-- status  0上架  1下架  上架状态不能删除商品 -->
          <el-button
            v-if="scope.row.status === '1' && isAdminRole ==='1'"
            class="text-button el-button--danger"
            size="mini"
            @click="handleDelete1(scope.row.id, scope.row.code)"
          >删除</el-button>
          <el-button
            v-if="scope.row.status === '0' && isAdminRole ==='1'"
            :disabled="scope.row.status === '0'"
            class="text-button"
            size="mini"
            @click="handleDelete1(scope.row.id, scope.row.code)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      :total-count="totalCount"
      :page.sync="listQuery.pageNo"
      :limit.sync="listQuery.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script>
import { commonMixin } from '@v/mixin/commonMixin.js'
import ComApiUrl from '@a/comomApi.js'
import pagination from '@/components/pagination/index.vue'
import { validNumber, validNum } from '@u/validate'
import { importProduct, uploadBatchPhoto, importInstock,
  updateStatusByCode, getGoodInfoByCode, deleteImgInfo, getOrgSiteByCode,
  getSite, siteAllocate, templateDownload, deleteGood } from '@a/business/goods.js'
import { mapGetters } from 'vuex'

export default {
  components: { pagination },
  mixins: [commonMixin],
  data() {
    const validateNumber = (rules, value, callback) => {
      if (!validNumber(value)) {
        callback(new Error('请输入大于0的正整数!'))
      } else {
        callback()
      }
    }
    const validateNum = (rules, value, callback) => {
      if (!validNum(value)) {
        callback(new Error('请输入大于0的数值!'))
      } else {
        callback()
      }
    }
    return {
      comApiUrlList: new ComApiUrl('/product/api/business/product/list'),
      comApiUrlAdd: new ComApiUrl('/product/api/business/product/add'),
      comApiUrlUpdate: new ComApiUrl('/product/api/business/product/update'),
      listQuery: {
        pageNo: 1,
        pageSize: 10
      },
      disabledCode: false,
      dialogTitle: '',
      dialogTitle_distribute: '库存分配',
      dialogFormVisible: false,
      dialogFormVisible_distribute: false,
      loading: false,
      checkResult: [],
      formData: {
        createAccount: '',
        mark: '',
        code: '',
        name: '',
        introduce: '',
        buyPrice: '',
        salePrice: '',
        productAddr: '',
        shipAddr: '',
        model: '',
        location: '',
        source: '',
        stock: '',
        photoList: []
      },
      formData_distribute: {
        code: '',
        site: '',
        stock: ''
      },
      rules: {
        code: [
          { required: true, message: '商品编码不能为空!', trigger: 'blur' }
        ],
        buyPrice: [
          { required: true, message: '成本价不能为空!', trigger: 'blur' },
          { validator: validateNum, trigger: 'blur' }
        ],
        salePrice: [
          { required: true, message: '出售价不能为空!', trigger: 'blur' },
          { validator: validateNum, trigger: 'blur' }
        ],
        stock: [
          { required: true, message: '库存数量不能为空!', trigger: 'blur' },
          { validator: validateNumber, trigger: 'blur' }
        ],
        name: [
          { required: true, message: '商品编码不能为空!', trigger: 'blur' }
        ]
      },
      rules_distribute: {
        code: [
          { required: true, message: '商品编码不能为空!', trigger: 'blur' }
        ],
        site: [
          { required: true, message: '分配站点不能为空!', trigger: 'blur' }
        ],
        stock: [
          { required: true, message: '分配数量不能为空!', trigger: 'blur' },
          { validator: validateNumber, trigger: 'blur' }
        ]
      },
      tableData: [],
      showPic: false,
      dialogType: '',
      updateFileList: [], // 修改模态框中显示的预览图
      isFile: false,
      uploadFile: null,
      fileType: '', // 上传文件类型  商品批量导入or库存批量导入
      siteList: [],
      isAdminRole: '',
      dialogFormVisible_detail: false,
      dialogTitle_detail: '',
      goodsDetail: {} // 详情
    }
  },
  computed: {
    ...mapGetters(['logisticsList'])
  },
  mounted() {
    const userInfo = JSON.parse(localStorage.getItem('userInfo'))
    this.formData.createAccount = userInfo.userId
    this.isAdminRole = userInfo.isAdminRole
    this.getList()
    setTimeout(() => {
      this.$nextTick(() => {
        this.$refs.table.doLayout()
      })
    }, 300)
  },
  methods: {
    // 删除新增或修改模块中的图片
    deleteInsertPic(file, detail) {
      if (this.dialogType === 'add') {
        this.updateFileList.splice(detail.index, 1)
      } else if (this.dialogType === 'edit') {
        console.log('编辑图片')
        this.$confirm('是否删除原有的商品图片?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteImgInfo(file.id).then(res => {
            if (res.code === 0) {
              this.$message({
                type: 'success',
                message: '删除成功！'
              })
              this.updateFileList.splice(detail.index, 1)
              this.getList()
            } else {
              this.$message({
                type: 'error',
                message: res.msg
              })
            }
          })
        })
      }
    },
    // 限制文件类型-jpeg
    beforeRead(file) {
      // console.log(file)
      if (file.type === 'image/png') {
        this.$notify.warning('请上传 jpg 格式图片')
        return false
      }
      return true
    },
    // 模板下载
    handleDownLoad() {
      templateDownload().then(res => {
        // const blob = new Blob([res.data]) // 低级错误
        const blob = new Blob([res])
        console.log(blob)
        const downloadElement = document.createElement('a')
        // 创建下载的链接
        const href = window.URL.createObjectURL(blob)
        downloadElement.href = href
        // 下载后的文件名
        downloadElement.download = `导入模板.zip`
        document.body.appendChild(downloadElement)
        downloadElement.click() // 下载
        // 下载完成 移除 a
        document.body.removeChild(downloadElement)
        // 释放blob对象
        window.URL.revokeObjectURL(href)
      })
    },
    // 新增or修改保存
    handleSave() {
      // photoList: [{ photoBase64: '', photoName: '' }] // 图片塞进服务器的接口标准格式
      console.log(this.updateFileList)
      const imgInfo = []
      this.updateFileList.forEach(item => {
        if (item.content) {
          imgInfo.push({ photoBase64: item.content.split(',')[1], photoName: item.file.name })
        }
      })
      this.formData.photoList = imgInfo
      console.log(this.formData)
      if (this.dialogType === 'add') {
        console.log('执行增加操作')
        this.$refs.formData.validate(valide => {
          // console.log(this.formData)
          valide ? this.create() : ''
        })
      } else if (this.dialogType === 'edit') {
        console.log('执行编辑操作')
        this.$refs.formData.validate(valide => {
          // console.log(this.formData)
          valide ? this.update() : ''
        })
        this.updateFileList = []
      }
    },
    // 新增商品信息
    handleAddGoods() {
      this.dialogFormVisible = true
      this.dialogTitle = '新增商品信息'
      this.updateFileList = []
      this.dialogType = 'add'
      this.disabledCode = false
    },
    // 修改商品信息
    handleEdit(code) {
      this.dialogFormVisible = true
      this.dialogTitle = '修改商品信息'
      this.dialogType = 'edit'
      this.tableData.length ? this.disabledCode = true : this.disabledCode = false
      getGoodInfoByCode(code).then(res => {
        if (res.code === 0) {
          this.formData = res.data
          const arr = [] // 回显图片
          res.data.photoList.forEach(item => {
            arr.push({ url: item.photoName, id: item.id })
          })
          this.updateFileList = arr
        } else {
          this.$message({
            type: 'error',
            message: res.msg
          })
        }
      })
    },
    // 上传多个文件时进行处理
    handleExceed(files, fileList) {
      this.$message.warning(`限制只能上传1个文件`)
    },
    // 上传之前要干的事情
    beforeFileUpload(file) {
      console.log(file)
      if (file) {
        this.isFile = true
        this.$confirm('文件选取成功,是否继续上传?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(res => { this.submitUpload() })
      } else { return }
      const isLt50M = file.size / 1024 / 1024 < 50
      // txt文件'text/plain' csv文件'application/vnd.ms-excel'
      const temp = file.name.split('.')
      if (temp[temp.length - 1] === 'xls' || temp[temp.length - 1] === 'zip') {
        if (isLt50M) {
          console.log(this.uploadFile)
          this.uploadFile = file
          console.log(this.uploadFile)
        } else {
          // this.$message.warning('上传文件大小超出50MB!')
          this.$message({
            type: 'error',
            message: '上传文件大小超出50MB!'
          })
        }
      } else {
        // this.$message.warning('上传文件只能是xls文件!')
        this.$message({
          type: 'error',
          message: '上传文件只能是zip文件!'
        })
      }
      return false
    },
    beforeFileUpload1(file) {
      const isLt50M = file.size / 1024 / 1024 < 50
      const temp = file.name.split('.')
      if (temp[temp.length - 1] === 'zip') {
        if (isLt50M) {
          this.uploadFile = file
        } else {
          this.$message({
            type: 'error',
            message: '上传文件大小超出50MB!'
          })
        }
        if (file) {
          this.isFile = true
          this.submitUpload()
        } else { return }
      } else {
        this.$message({
          type: 'error',
          message: '请上传zip文件！'
        })
      }
      return false
    },
    submitUpload() {
      console.log('开始上传excel文件啦')
      if (this.isFile) {
        const params = new FormData()
        params.append('file', this.uploadFile)
        const userInfo = JSON.parse(localStorage.getItem('userInfo'))
        params.append('userId', userInfo.userId)
        const fileType = this.fileType
        console.log(fileType)
        console.log(params)
        switch (fileType) {
          case 'importGoods':
            importProduct(params).then(res => { this.messageAlert(res) })
            break
          case 'importImg':
            // uploadBatchPhoto(params).then(res => { this.messageAlert(res) })
            uploadBatchPhoto(params).then(res => {
              console.log(res)
              if (res.code === 0) {
                if (res.data.result) {
                  this.$message({ type: 'success', message: res.data.result })
                  location.reload()
                } else {
                  this.$message({ type: 'success', message: res.msg })
                  location.reload()
                }
                this.getList()
              } else {
                this.$message({ type: 'error', message: res.msg })
                this.getList()
                location.reload()
              }
            })
            break
          case 'importStock':
            importInstock(params).then(res => { this.messageAlert(res) })
            break
          default: ''
        }
      } else {
        this.$message({
          message: '请选取文件后再上传!',
          type: 'warning'
        })
      }
    },
    // 统一上传成功后的回调
    messageAlert(res) {
      if (res.code === 0) {
        this.$message({ type: 'success', message: res.msg })
        this.getList()
      } else {
        this.$message({ type: 'error', message: res.msg })
        this.getList()
      }
    },
    uploadFileType(val) {
      console.log(val)
      switch (val) {
        case 'importGoods':
          this.fileType = 'importGoods'
          break
        case 'importImg':
          this.fileType = 'importImg'
          break
        case 'importStock':
          this.fileType = 'importStock'
          break
        default: ''
      }
    },
    // 详情（旧）
    handleDetail1(code) {
      this.$router.push('/business/goods/detail/' + code)
    },
    // 详情（新）
    handleDetail(code) {
      this.dialogTitle_detail = '商品详情'
      this.dialogFormVisible_detail = true
      getGoodInfoByCode(code).then(res => {
        console.log(res)
        if (res.code === 0) {
          this.goodsDetail = res.data
        } else {
          this.$message({
            type: 'error',
            message: res.msg
          })
        }
      })
    },
    // 关闭详情
    closeDialogFormVisible_detail() {
      this.dialogFormVisible_detail = false
    },
    // 下架
    handleOutshelf(status, code) {
      // 处于已上架状态，status为1；处于已下架状态，status为0
      // 要上架就传0，要下架就传1
      if (status === '0') {
        this.$confirm('是否确认下架?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: ''
        }).then(() => { this.updateStatusShlft('1', code) })
      } else if (status === '1') {
        this.$confirm('是否确认上架?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: ''
        }).then(() => { this.updateStatusShlft('0', code) })
      }
    },
    // 上下架
    updateStatusShlft(status, code) {
      updateStatusByCode(status, code).then(res => {
        // console.log(res)
        if (res.code === 0) {
          this.$message({
            type: 'success',
            message: res.msg
          })
        } else {
          this.$message({
            type: 'error',
            message: res.msg
          })
        }
        this.getList()
      })
    },
    // 入库
    handleImportStore(code) {
      this.$router.push('/business/goods/importStore/' + code)
    },
    // 分配
    handleDistribute(code) {
      console.log(code)
      this.dialogFormVisible_distribute = true
      this.formData_distribute.code = code
      getSite({}).then(res => {
        if (res.code === 0) {
          this.siteList = res.data
        } else {
          this.$message({
            type: 'error',
            message: res.msg
          })
        }
      })
    },
    // 关闭
    handleClose() {
      this.dialogFormVisible = false
      this.$refs.formData.resetFields()
    },
    // 确认分配
    handleSave_distribute() {
      console.log(this.formData_distribute)
      this.$refs.formData_distribute.validate(valide => {
        if (valide) {
          siteAllocate(this.formData_distribute).then(res => {
            if (res.code === 0) {
              this.$message({
                type: 'success',
                message: '分配成功！'
              })
              this.dialogFormVisible_distribute = false
              this.getList()
            } else {
              this.$message({
                type: 'error',
                message: res.msg
              })
            }
          })
        }
      })
    },
    close_distribute() {
      this.dialogFormVisible_distribute = false
    },
    closeDialog1() {
      this.$refs.formData_distribute.resetFields()
    },
    // 删除商品
    handleDelete1(id, code) {
      console.log(id)
      getOrgSiteByCode(code).then(res => {
        if (res.code === 0) {
          console.log(res.data)
          const dataList = res.data
          this.deleteData(dataList, id)
        }
      })
    },
    // 确认删除提醒
    deleteData(dataList, id) {
      if (dataList) {
        this.$confirm(dataList + '存在该商品，将同步删除，是否确定?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.deleteApi(id)
        })
      } else {
        this.$confirm('确认删除?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.deleteApi(id)
        })
      }
    },
    // 删除接口
    deleteApi(id) {
      deleteGood(id).then(res => {
        if (res.code === 0) {
          this.$message({
            type: 'success',
            message: '删除成功'
          })
          this.getList()
        } else {
          this.$message({
            type: 'error',
            message: res.msg
          })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.goodDetail {
  padding: 0 100px;
  // text-align: center;
}
.img1 {
  width: 100%;
  height: auto;
}
</style>
